package com.tulei.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.tulei.common.response.R;
import com.tulei.common.utils.MinioUtils;
import com.tulei.common.utils.StringUtils;
import com.tulei.system.Entity.SysUser;
import com.tulei.system.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author TuLei
 * @Date 2024-06-16 13:44
 **/

@RequiredArgsConstructor
@RestController
@RequestMapping("api/user/profile")
public class SysProfileController {

    private final MinioUtils minioUtils;

    private final UserService userService;
    @GetMapping
    public R<SysUser> profile()
    {
        SysUser user = (SysUser) StpUtil.getSession().get("user");

        return R.ok(user);
    }


    @PostMapping("/avatar")
    public R<Map<String, String>> avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception
    {
        if (!file.isEmpty()) {
            Long userId = (long) Integer.parseInt(StpUtil.getLoginId().toString());
            String avatar = minioUtils.upload(file, "avatar");
            if (userService.updateUserAvatar(userId, avatar))
            {
                HashMap<String, String> map = new HashMap<>();
                map.put("avatar", avatar);
                return R.ok(map);
            }

        }
        return R.fail("上传图片异常，请联系管理员");
    }


    @PutMapping
    public R<Void> updateProfile(@RequestBody SysUser user)
    {
        SysUser currentUser = (SysUser) StpUtil.getSession().get("user");
        currentUser.setNickName(user.getNickName());
        currentUser.setEmail(user.getEmail());
        currentUser.setPhone(user.getPhone());
        currentUser.setSex(user.getSex());

        if (StringUtils.isNotEmpty(user.getPhone()) && !userService.checkPhoneUnique(currentUser))
        {
            return R.fail("修改用户'" + currentUser.getUsername() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(currentUser))
        {
            return R.fail("修改用户'" + currentUser.getUsername() + "'失败，邮箱账号已存在");
        }
        if (userService.updateUserProfile(currentUser) > 0)
        {
            // 更新缓存用户信息
            StpUtil.getSession().set("user", currentUser);
            return R.ok();
        }
        return R.fail("修改个人信息异常，请联系管理员");
    }
}
